<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="5">
              <a-form-item label="名称">
                <a-input
                  v-model="queryParam.ruleName"
                  placeholder="请输入名称"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>

            <a-col :span="5">
              <a-form-item label="城市区域" prop="type">
                <a-select
                  placeholder="所在城市"
                  v-model="queryParam.ruleCities"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="(d, index) in cityOptions"
                    :key="index"
                    :value="d.name.replace('市', '')"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="客户来源" prop="type">
                <a-select
                  placeholder="选择客户来源"
                  v-model="queryParam.laiyuan"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="(d, index) in laiyuanOptions"
                    :key="index"
                    :value="d.dictValue"
                    >{{ d.dictLabel }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />重置</a-button
                >
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? "收起" : "展开" }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 类型选择 -->
      <biz-push-rule-type-modal
        v-if="showTypeModal"
        ref="bizPushRuleTypeModal"
        :ruleSetOptions="ruleSetOptions"
        @ok="typeModalOk"
        @close="showTypeModal = false"
      />

      <biz-push-rule-by-user-add-form
        v-if="showByUserAddModal"
        ref="bizPushRuleByUserAddForm"
        :ruleTypeOptions="ruleTypeOptions"
        :laiyuanOptions="laiyuanOptions"
        :tagsOptions="tagsOptions"
        :statusOptions="statusOptions"
        :cityOptions="cityOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        :ruleLogicOptions="ruleLogicOptions"
        @ok="getList"
        @close="showByUserAddModal = false"
      />
      <biz-push-rule-by-user-edit-form
        v-if="showByUserEditModal"
        ref="bizPushRuleByUserEditForm"
        :ruleTypeOptions="ruleTypeOptions"
        :laiyuanOptions="laiyuanOptions"
        :tagsOptions="tagsOptions"
        :statusOptions="statusOptions"
        :cityOptions="cityOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        :ruleLogicOptions="ruleLogicOptions"
        @ok="getList"
        @close="showByUserEditModal = false"
      />

      <!-- 增加 -->
      <biz-push-rule-add-form
        v-if="showAddModal"
        ref="bizPushRuleAddForm"
        :ruleTypeOptions="ruleTypeOptions"
        :laiyuanOptions="laiyuanOptions"
        :tagsOptions="tagsOptions"
        :statusOptions="statusOptions"
        :cityOptions="cityOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        :ruleLogicOptions="ruleLogicOptions"
        @ok="getList"
        @close="showAddModal = false"
      />
      <!-- 编辑 -->
      <biz-push-rule-edit-form
        v-if="showEditModal"
        ref="bizPushRuleEditForm"
        :ruleTypeOptions="ruleTypeOptions"
        :laiyuanOptions="laiyuanOptions"
        :tagsOptions="tagsOptions"
        :statusOptions="statusOptions"
        :cityOptions="cityOptions"
        :deptOptions="deptOptions"
        :expandedKeys="expandedKeys"
        :ruleLogicOptions="ruleLogicOptions"
        @ok="getList"
        @close="showEditModal = false"
      />
      <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane key="1" tab="按人员分配规则"> </a-tab-pane>
        <a-tab-pane key="2" tab="自定义规则"> </a-tab-pane>
      </a-tabs>
      <advance-table
        title="分配规则"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        tableKey="base-bizPushRule-index-table"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="bizPushRuleList"
        :loading="loading"
        :format-conditions="true"
      >
        <div class="table-operations" slot="button">
          <a-button
            type="primary"
            @click="handleAdd()"
            v-hasPermi="['biz:bizPushRule:add']"
            v-if="queryParam.ruleSet === '2'"
          >
            <a-icon type="plus" />新增
          </a-button>

          <!-- <a-button
            type=""
            @click="handleExport"
            v-hasPermi="['biz:bizPushRule:export']"
          >
            <a-icon type="download" />导出
          </a-button> -->
          <a-button
            type="danger"
            v-if="!multiple"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:bizPushRule:remove']"
          >
            <a-icon type="delete" />删除
          </a-button>
        </div>

        <span slot="ruleType" slot-scope="{ record }">
          {{ ruleTypeFormat(record) }}
        </span>

        <span slot="ruleSet" slot-scope="{ record }">
          {{ ruleSetFormat(record) }}
        </span>
        <span slot="ruleLogic" slot-scope="{ record }">
          {{ ruleLogicFormat(record) }}
        </span>

        <span slot="tags" slot-scope="{ record }">
          {{ tagsFormat(record) }}
        </span>

        <span slot="status" slot-scope="{ record }">
          {{ statusFormat(record) }}
        </span>

        <span slot="operation" slot-scope="{ text, record }">
          <a
            @click="handleUpdate(record)"
            v-hasPermi="['biz:bizPushRule:edit']"
          >
            修改
          </a>
          <a-divider type="vertical" v-hasPermi="['biz:bizPushRule:remove']" />
          <a
            @click="handleDelete(record)"
            v-hasPermi="['biz:bizPushRule:remove']"
          >
            删除
          </a>
        </span>
        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>
        <span slot="laiyuan" slot-scope="{ record }">
          <span v-if="record.laiyuan">
            {{ ruleTextFormat(record.laiyuan) }}
          </span>
          <span v-else></span>
        </span>
        <span slot="ruleCities" slot-scope="{ record }">
          <span v-if="record.ruleCities">
            {{ ruleTextFormat(record.ruleCities) }}
          </span>
          <span v-else></span>
        </span>

        <span slot="jiedanInfo" slot-scope="{ text, record }">
          <template v-if="text">
            <span v-for="(item, index) in record.ruleUsers" :key="index">
              <span v-if="item.isEnable == '0'" style="color: gray"
                >{{ item.laiyuan }}[{{ item.maxCount }}-{{ item.sharedCount }}]
              </span>
              <span v-else>
                {{ item.laiyuan }}
                <span
                  v-if="item.sharedCount && item.sharedCount > 0"
                  style="color: red"
                  >[{{ item.maxCount }}-{{ item.sharedCount }}]
                </span>
                <span v-else style="color: green"
                  >[{{ item.maxCount }}-{{ item.sharedCount }}]
                </span>
              </span>
            </span>
          </template>
          <span v-else>
            {{ "" }}
          </span>
        </span>
        <span slot="sumCount" slot-scope="{ record }">
          <template v-if="record.ruleUsers">
            <span>
              {{
                record.ruleUsers.reduce(
                  (sum, user) => sum + (user.sharedCount || 0),
                  0
                )
              }}
            </span>
          </template>
          <span v-else>
            {{ "" }}
          </span>
        </span>

        <span slot="totalCount" slot-scope="{ record }">
          <template v-if="record.ruleUsers">
            <span>
              {{
                record.ruleUsers.reduce(
                  (sum, user) => sum + (user.totalCount || 0),
                  0
                )
              }}
            </span>
          </template>
          <span v-else>
            {{ "" }}
          </span>
        </span>
      </advance-table>
    </a-card>
  </div>
</template>
<script>
import {
  listBizPushRule,
  delBizPushRule,
  exportBizPushRule,
} from "@/api/biz/bizPushRule";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import BizPushRuleAddForm from "@/views/biz/pushrule/modules/BizPushRuleAddForm";
import BizPushRuleEditForm from "@/views/biz/pushrule/modules/BizPushRuleEditForm";
import BizPushRuleTypeModal from "@/views/biz/pushrule/modules/BizPushRuleTypeModal";
import BizPushRuleByUserAddForm from "@/views/biz/pushrule/modules/BizPushRuleByUserAddForm";
import bizPushRuleByUserEditForm from "@/views/biz/pushrule/modules/BizPushRuleByUserEditForm";
import { findListByCode } from "@/api/biz/sysArea";
import { listDeptTree } from "@/api/system/dept";
export default {
  name: "BizPushRule",
  components: {
    AdvanceTable,
    BizPushRuleAddForm,
    BizPushRuleEditForm,
    BizPushRuleTypeModal,
    BizPushRuleByUserAddForm,
    bizPushRuleByUserEditForm,
  },
  data() {
    return {
      showTypeModal: false,
      showAddModal: false,
      showEditModal: false,
      showByUserAddModal: false,
      showByUserEditModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 分配规则表格数据
      bizPushRuleList: [],
      // 分配类型字典
      ruleTypeOptions: [],
      // 客户来源字典
      laiyuanOptions: [],
      // 标签字典
      tagsOptions: [],
      // 状态字典
      statusOptions: [],
      // 城市
      cityOptions: [],
      // 部门
      deptOptions: [],
      // 部门树默认展开的keys
      expandedKeys: [],
      // 分配方式
      ruleLogicOptions: [],
      // 分配设置
      ruleSetOptions: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        ruleName: undefined,

        // 客户分配
        ruleType: "0",

        ruleSet: "1",
        // 单一来源分配
        ruleLogic: "1",

        cityName: undefined,

        laiyuan: undefined,

        status: undefined,

        userId: undefined,
      },
      columns: [],
      // 自定义分配规则表格列
      columnsCustomize: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "30px",
          scopedSlots: { customRender: "rowindex" },
        },

        {
          title: "名称",
          dataIndex: "ruleName",
          ellipsis: true,
          align: "center",
          width: "100px",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          ellipsis: true,
          align: "center",
          width: "100px",
        },

        {
          title: "城市名称",
          dataIndex: "ruleCities",
          ellipsis: true,
          align: "center",
          width: "60px",
          scopedSlots: { customRender: "ruleCities" },
        },
        {
          title: "客户来源",
          dataIndex: "laiyuan",
          align: "center",
          width: "500px",
          scopedSlots: { customRender: "laiyuan" },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "60px",
          scopedSlots: { customRender: "operation" },
        },
      ],
      // 按人员分配规则表格列
      columnsByUser: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "30px",
          scopedSlots: { customRender: "rowindex" },
        },

        {
          title: "姓名",
          dataIndex: "ruleName",
          ellipsis: true,
          align: "center",
          width: "60px",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          ellipsis: true,
          align: "center",
          width: "100px",
        },

        {
          title: "城市名称",
          dataIndex: "ruleCities",
          ellipsis: true,
          align: "center",
          width: "60px",
          scopedSlots: { customRender: "ruleCities" },
        },

        {
          title: "客户来源",
          // dataIndex: "laiyuan",
          align: "center",
          width: "400px",
          scopedSlots: { customRender: "jiedanInfo" },
        },
        {
          title: "当日合计接单量",
          // dataIndex: "sumCount",
          align: "center",
          width: "80px",
          // fixed: "left",
          scopedSlots: { customRender: "sumCount" },
        },
        {
          title: "当日最大接单量",
          dataIndex: "maxCount",
          align: "center",
          width: "80px",
          // fixed: "left",
          // scopedSlots: { customRender: "maxCount" },
        },
        {
          title: "累计总接单量",
          // dataIndex: "totalCount",
          align: "center",
          width: "80px",
          // fixed: "left",
          scopedSlots: { customRender: "totalCount" },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "60px",
          scopedSlots: { customRender: "operation" },
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getDicts("pushrule_type").then((response) => {
      this.ruleTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.laiyuanOptions = response.data;
    });
    this.getDicts("sys_common_status").then((response) => {
      this.tagsOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("rule_logic_options").then((response) => {
      this.ruleLogicOptions = response.data;
    });
    this.getDicts("pushrule_set").then((response) => {
      this.ruleSetOptions = response.data;
    });

    this.handleFindCityList();
    this.getTreeselect();
  },
  methods: {
    /** tab选显卡操作 */
    callback(v) {
      this.queryParam.ruleSet = v;
      this.handleQuery();
    },

    typeModalOk(ruleSet) {
      if (ruleSet === "1") {
        this.showByUserAddModal = true;
        this.$nextTick(() =>
          this.$refs.bizPushRuleByUserAddForm.handleAdd(
            this.queryParam.ruleType
          )
        );
      } else {
        this.showAddModal = true;
        this.$nextTick(() =>
          this.$refs.bizPushRuleAddForm.handleAdd(this.queryParam.ruleType)
        );
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDeptTree("0", 3, 2, 1).then((response) => {
        this.deptOptions = response.data;
        this.getExpandedKeys(this.deptOptions, 2);
      });
    },
    getExpandedKeys(nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        if (nodes != null) {
          nodes.forEach((node) => {
            this.expandedKeys.push(node.id);
            expandLevel = expandLevel - 1;
            return this.getExpandedKeys(node.children, expandLevel);
          });
        }
      }
    },
    // 获取城市区域列表
    handleFindCityList() {
      findListByCode().then((res) => {
        this.cityOptions = res.data;
      });
    },
    /** 查询分配规则列表 */
    getList() {
      if (this.queryParam.ruleSet === "1") {
        this.queryParam.ruleLogic = "1";
        this.columns = this.columnsByUser;
      } else {
        this.queryParam.ruleLogic = "1";
        this.columns = this.columnsCustomize;
      }

      this.loading = true;
      listBizPushRule(this.queryParam).then((response) => {
        this.bizPushRuleList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 分配类型字典翻译
    ruleTypeFormat(row) {
      if (row.ruleType) {
        return this.selectDictLabel(this.ruleTypeOptions, row.ruleType);
      } else {
        return "";
      }
    },

    // 分配设置字典翻译
    ruleSetFormat(row) {
      if (row.ruleSet) {
        return this.selectDictLabel(this.ruleSetOptions, row.ruleSet);
      } else {
        return "";
      }
    },
    // 分配方式字典翻译
    ruleLogicFormat(row) {
      if (row.ruleLogic) {
        return this.selectDictLabel(this.ruleLogicOptions, row.ruleLogic);
      } else {
        return "";
      }
    },

    // 字符串处理:去掉中括号和双引号
    ruleTextFormat(text) {
      if (text && text.length > 0) {
        return text.replace("[", "").replace("]", "").replace(/"/g, "");
      } else {
        return "";
      }
    },

    // 客户来源字典翻译
    laiyuanFormat(row) {
      if (row.laiyuan) {
        return this.selectDictLabels(this.laiyuanOptions, row.laiyuan);
      } else {
        return "";
      }
    },
    // 标签字典翻译
    tagsFormat(row) {
      if (row.tags) {
        return this.selectDictLabel(this.tagsOptions, row.tags);
      } else {
        return "";
      }
    },
    // 状态字典翻译
    statusFormat(row) {
      if (row.status) {
        return this.selectDictLabel(this.statusOptions, row.status);
      } else {
        return "";
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = 10;
      this.queryParam.ruleName = undefined;
      this.queryParam.ruleCities = undefined;
      this.queryParam.laiyuan = undefined;
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd() {
      const ruleSet = this.queryParam.ruleSet;
      if (ruleSet === "1") {
        this.showByUserAddModal = true;
        this.$nextTick(() =>
          this.$refs.bizPushRuleByUserAddForm.handleAdd(
            this.queryParam.ruleType
          )
        );
      } else {
        this.showAddModal = true;
        this.$nextTick(() =>
          this.$refs.bizPushRuleAddForm.handleAdd(this.queryParam.ruleType)
        );
      }
    },
    handleUpdate(record) {
      // 根据分配类型显示不同编辑页面
      if (record.ruleSet === "2") {
        this.showEditModal = true;
        this.$nextTick(() =>
          this.$refs.bizPushRuleEditForm.handleUpdate(record)
        );
      } else {
        record.ruleType = this.queryParam.ruleType;
        record.ruleSet = this.queryParam.ruleSet;
        record.ruleLogic = "1";
        if (record.id === record.userId) {
          this.showByUserAddModal = true;
          this.$nextTick(() =>
            this.$refs.bizPushRuleByUserAddForm.handleAdd(record)
          );
        } else {
          this.showByUserEditModal = true;
          this.$nextTick(() =>
            this.$refs.bizPushRuleByUserEditForm.handleUpdate(record)
          );
        }
      }

      // this.showEditModal = true;
      // this.$nextTick(() =>
      //   this.$refs.bizPushRuleEditForm.handleUpdate(record, ids)
      // );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const bizPushRuleIds = row.id || this.ids;
      this.$confirm({
        title: "确认删除所选中数据?",
        onOk() {
          return delBizPushRule(bizPushRuleIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportBizPushRule(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
  },
};
</script>
